/**
 * 开单页中显示商品信息模块
 * 主要逻辑为，如果第一个商品选择的是本科室的商品，后续的商品只能限制选择本科室的（商品名前带了👑图标的为本科室商品）
 * 如果第一个商品选择的是其他科室的商品，后续的商品只能选择非本科室的商品
 */
import React, { useState, useRef, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Divider, Button, Tooltip, Form, message, Row, Col } from 'antd';
import { EditableProTable } from '@ant-design/pro-table';
import { RedoOutlined, PlusOutlined } from '@ant-design/icons';
import { OptType } from '@/utils/constants';
import { useModel } from 'umi';
import type { FormInstance } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import {
  getGoodsSpecsList
} from '@/services/stock-goods/api';
import GoodName from '@/components/Select/GoodName';
import { isNull, showMsg, isSupportSticky } from '@/utils/utils';
import styles from './style.less';
import { getSubGoodsSpecsList } from '@/services/stock-goods/subApi';

interface ItemInfoProps {
  type?: string,
  updateGoodsList: (goodsList: any) => void;
  list?: STOCKGOODSAPI.GoodsItem[];
  yuanlist?: STOCKGOODSAPI.GoodsItem[];
}

const ItemInfo: React.FC<ItemInfoProps> = forwardRef((props, ref) => {
  const {
    type,
    updateGoodsList,
    list,
    yuanlist,
  } = props;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [editForm] = Form.useForm();
  const { initialState } = useModel('@@initialState');

  // 数据
  const [dataSource, setDataSource] = useState<any[]>(list || []);

  // 新增数量
  const [newAddNums, setNewAddNums] = useState<number>(0);

  // 更新数
  const [updateNums, setUpdateNums] = useState<number>(0);

  // 删除数
  const [deleteNums, setDeleteNums] = useState<number>(0);

  // 选中的第一个商品科室code
  const [filterVal, setFilterVal] = useState('');

  // 当前选中的行编号，用于定位颜色
  const [clickRow, setClickRow] = useState('');


  // 获得当前rowKey的dataSource数据
  const getRowByKey = (rowKey) => {
    return dataSource.filter(item => item.id === rowKey);
  }

  const ggChange = (specItem, form, rowKey, fromData) => {
    const goodsItem: STOCKGOODSAPI.GoodsItem = form.getFieldsValue()[rowKey as string];
    // console.log('goodsItem', goodsItem)
    goodsItem.goods_num = 1;
    goodsItem.specs_id = specItem.specs_id;
    goodsItem.discount = 1.0;
    goodsItem.discount_price = Number(specItem?.selling_price as number) * 1 * 1.0;
    form.setFieldsValue({ [rowKey || '']: goodsItem });


    const result = fromData.findIndex(item => item.id === rowKey);
    if (result > -1) {
      fromData[result].goods_price = specItem?.selling_price;
      fromData[result].goods_num = 1;
      fromData[result].goods_total_price = Number(specItem?.selling_price as number) * 1;
      fromData[result].discount = 1.0;
      fromData[result].discount_price = Number(specItem?.selling_price as number) * 1 * 1.0;
      fromData[result].specs_id = specItem.specs_id;
      fromData[result].specs_name = specItem.specs_name;
      fromData[result].can_inventory = specItem.can_inventory;
      // console.log('dataSourceaaa', dataSource)
      setDataSource(Object.assign([], fromData));
      updateGoodsList(Object.assign([], fromData));
      checkChange(fromData);
    }
  }

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    isNull: () => dataSource.length === 0,
    validate: () => {
      return editForm.validateFields().then(values => {
        const result = dataSource.filter(item => !item.disabled);
        return isNull(result) || !result;
      }).catch(errorInfo => {
        return false;
      });
    },
    clear: () => {
      setNewAddNums(0);
      setUpdateNums(0);
      setDeleteNums(0);
      setDataSource([]);
      setEditableRowKeys([]);
      editForm.resetFields();
      actionRef.current?.reload();
    },
    addLine: () => {
      const id = `new_${Date.now()}`;
      setDataSource([{
        id, specsList: [], disabled: false,
      }]);
      setEditableRowKeys([id]);
    },
  }))

  // 判断是否添加了重复的规格
  const checkSpecsIsexits = (specs_id) => {
    const result = dataSource.filter(item => item.specs_id === specs_id);
    return !isNull(result)
  }

  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '分类',
      dataIndex: 'class_name',
      editable: false,
      width: 80
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      valueType: 'select',
      width: 190,
      // editable: (val, record) => record.disabled,
      fieldProps: (val, { entity }) => {
        return {
          disabled: entity.disabled,
        }
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项'
          }
        ]
      },
      renderFormItem: (form1, record1, form, e) => {
        // console.log('form1, record1', form1, form, e)
        const record = form1.entity;
        // console.log('record1', record1, record)
        // value={`${record.goods_id}|${record.goods_py}|${record.brand_name}|${record.goods_name}`}
        return (
          <GoodName disabled={record.disabled} noStyle allowClear={false}
            name1={`goods_name_${record1.recordKey}_${form1.index}`} value1={record.goods_id}
            filterVal={form1.index === 0 ? '' : filterVal}
            onChange={e => {
              // console.log('选中的商品', e);
              const obj = {
                class_name: e.class_name,
                goods_id: e.goods_id,
                goods_name: e.goods_name,
                brand_id: e.brand_id,
                brand_name: e.brand_name,
                obj: e,
                id: record1.recordKey,
                goods_dept_code: e.create_dept_code,
                specs_id: null,
                specs_name: null,
                goods_price: null,
                goods_num: null,
                goods_total_price: null,
                discount: null,
                discount_price: null,
                remarks: null
              }
              const result = dataSource.findIndex(item => item.id === record1.recordKey);

              if (result > -1) {
                form.setFieldsValue({ [record1.recordKey]: obj })
                if (form1.index === 0) {
                  if (!isNull(filterVal) && e.create_dept_code !== filterVal) {
                    setDataSource(Object.assign([], [obj]));
                    fetchGoodsSpecsList(e.goods_id, e.create_dept_code, 0, [obj], form, record1.recordKey);
                    setFilterVal(e.create_dept_code);
                    return;
                  }
                  setFilterVal(e.create_dept_code);
                }
                dataSource[result] = obj;
                setDataSource(Object.assign([], dataSource));
                fetchGoodsSpecsList(e.goods_id, e.create_dept_code, result, dataSource, form, record1.recordKey);
              }
            }}
          />
        )
      },
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      editable: false,
      width: 100,
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_id',
      valueType: 'select',
      width: 160,
      fieldProps: (form, record) => {
        // console.log('规格', record, dataSource);
        // template_content
        const { obj, specsList } = dataSource[record.rowIndex] ?? {};
        return {
          disabled: record.entry.disabled,
          dropdownMatchSelectWidth: false,
          optionLabelProp: "text",
          size: 'small',
          options: specsList?.map(item => {
            let num = 0;
            // 编辑时，之前选的商品规格库存为0，就默认为订单选择的数量
            if (type === 'edit' && item.can_inventory <= 0 && record.entry.specs_id === item.specs_id) {
              num = record.entry.goods_num;
            } else {
              num = item.can_inventory;
            }
            const disabled = num < 1; // 库存不足
            const isexits = checkSpecsIsexits(item.specs_id); // 规格是否存在
            const specValue: {} = item.template_value || {};
            return {
              className: styles.specSelectOption,
              label: (
                <Row gutter={8}>
                  {
                    obj?.template_content?.map((key, idx) =>
                      <Col key={idx}>
                        <span className='spec-option-label'>{key}</span>
                        <span className='spec-option-value'>{specValue[key]}</span>
                      </Col>
                    )
                  }
                  <Col> 库存 {disabled ? 0 : num}</Col>
                </Row>
              ),
              text: item.specs_name,
              value: item.specs_id as string,
              disabled: disabled || isexits,
            }
          }),
          showSearch: true,
          allowClear: false,
          onChange: (value: any) => {
            const specItem = (dataSource[record.rowIndex].specsList || []).find(item => item.specs_id === value);
            ggChange(specItem, form, record.rowKey, dataSource);
            return;
            const goodsItem: STOCKGOODSAPI.GoodsItem = form.getFieldsValue()[record.rowKey as string];
            goodsItem.goods_num = 1;
            goodsItem.specs_id = specItem.specs_id;
            goodsItem.discount = 1.0;
            goodsItem.discount_price = Number(specItem?.selling_price as number) * 1 * 1.0;
            form.setFieldsValue({ [record.rowKey || '']: goodsItem });


            const result = dataSource.findIndex(item => item.id === record.rowKey);
            if (result > -1) {
              dataSource[result].goods_price = specItem?.selling_price;
              dataSource[result].goods_num = 1;
              dataSource[result].goods_total_price = Number(specItem?.selling_price as number) * 1;
              dataSource[result].discount = 1.0;
              dataSource[result].discount_price = Number(specItem?.selling_price as number) * 1 * 1.0;
              dataSource[result].specs_id = specItem.specs_id;
              dataSource[result].specs_name = specItem.specs_name;
              dataSource[result].can_inventory = specItem.can_inventory;
              // console.log('dataSourceaaa', dataSource)
              setDataSource(Object.assign([], dataSource));
              updateGoodsList(Object.assign([], dataSource));
              checkChange(dataSource);
            }
          },
          filterOption: (inputVal, option) => (option.text.indexOf(inputVal) > -1)
        }
      },
      formItemProps: {
        rules: [
          {
            // required: true,
            message: '此项是必填项'
          }
        ]
      }
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      editable: false,
      valueType: 'money',
      align: 'right',
      width: 76
    },
    {
      title: '数量',
      dataIndex: 'goods_num',
      valueType: 'digit',
      width: 60,
      align: 'right',
      // editable: (val, record) => isNull(record.disabled) || !record.disabled,
      fieldProps: (form, { rowKey, rowIndex, entity }) => {
        return {
          disabled: entity.disabled,
          precision: 0,
          style: {
            width: '100%'
          },
          // min: 1,
          onChange: (value: number) => {
            if (isNull(value) || value < 1) {
              return;
            }
            const goodsItem = getRowByKey(rowKey)[0];
            if (goodsItem.goods_price) {
              const price = parseFloat(Number(goodsItem.goods_price) * value).toFixed(2);
              goodsItem.goods_total_price = price;
              dataSource[rowIndex].goods_total_price = price;
            }
            if (goodsItem.discount) {
              const price = parseFloat(parseFloat(goodsItem.discount) * parseFloat(goodsItem.goods_total_price)).toFixed(2)
              goodsItem.discount_price = price;
              dataSource[rowIndex].goods_total_price = price;
            }
            goodsItem.goods_num = value;
            dataSource[rowIndex].goods_num = value;
            form.setFieldsValue({ [rowKey || '']: goodsItem });
            setDataSource(Object.assign([], dataSource));
            updateGoodsList(Object.assign([], dataSource));
            checkChange(Object.assign([], dataSource));
          }
        }
      },
      formItemProps: (myForm, record) => {
        const entry = record.entry;
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项'
            },
            {
              validator: (e, val) => {
                const yuanCount = isNull(yuanlist?.[record.rowIndex]) ? -10086 : yuanlist?.[record.rowIndex].goods_num;
                const curCount = (type !== 'edit' || yuanCount === -10086) ? entry.can_inventory : entry.can_inventory <= 0 ? yuanCount : entry.can_inventory;
                if (val < 1) {
                  return Promise.reject(new Error(`数量最少为1!`));
                }
                if (val > curCount) {
                  return Promise.reject(new Error(`最多可退1!`));
                }
                return Promise.resolve();
              },
              message: `数量最少为 1，最多为 ${(type !== 'edit' ? entry.can_inventory : entry.can_inventory <= 0 ? entry.goods_num : entry.can_inventory) ?? ''}`
            },
          ]
        }
      }
    },
    {
      title: '原价',
      dataIndex: 'goods_total_price',
      editable: false,
      valueType: 'money',
      align: 'right',
      width: 76
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      valueType: 'digit',
      tooltip: "如：9折输入0.9",
      width: 56,
      align: 'right',
      editable: initialState?.canDiscount,
      fieldProps: (val, { entity }) => {
        return {
          // min: 0.01,
          // max: 1,
          precision: 2,
          style: {
            width: '100%'
          },
          disabled: entity.disabled,
        }

      },
      // editable: (val, record) => isNull(record.disabled) || !record.disabled,
      formItemProps: (form, { rowKey, rowIndex }) => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项'
            },
            {
              validator: (_, value) => {
                // console.log('value', value, value <= 0 || value > 1);
                if (value <= 0) {
                  return Promise.reject(new Error('不能为0'));
                }
                if (value > 1) {
                  return Promise.reject(new Error('最大为1'));
                }
                return Promise.resolve();
              },
              message: '折扣范围：0.01-1',
            },
          ],
          onChange: (e: any) => zkChange(parseFloat(e.target.value), rowKey, rowIndex, form),
          onBlur: (e) => zkChange(parseFloat(e.target.value), rowKey, rowIndex, form, 'blur'),
        }
      }
    },
    {
      title: '折扣价',
      dataIndex: 'discount_price',
      valueType: initialState?.canDiscount ? 'digit' : 'money',
      align: 'right',
      width: 76,
      editable: initialState?.canDiscount,
      fieldProps: (val, { entity }) => {
        return {
          // min: 0.01,
          // max: 1,
          precision: 2,
          style: {
            width: '100%'
          },
          disabled: entity.disabled,
        }
      },
      formItemProps: (form, { rowKey, rowIndex }) => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项'
            },
            {
              validator: (_, value) => {
                // console.log('z折扣价validator', value);
                if (value <= 0) {
                  return Promise.reject(new Error('不能为0'));
                }
                return Promise.resolve();
              },
              message: '折扣价不能为0',
            },
          ],
          onChange: (e: any) => zkjChange(parseFloat(e.target.value), rowKey, rowIndex, form),
          onBlur: (e) => zkjChange(parseFloat(e.target.value), rowKey, rowIndex, form, 'blur'),
        }
      }
    },
    {
      title: '备注',
      width: 88,
      dataIndex: 'remarks',
      valueEnum: row => {
        if (row.class_name === '镜片') {
          const tmpArr = dataSource.filter(({ remarks }) => remarks?.includes('镜片'));
          if (tmpArr.length >= 2) {
            return undefined as any;
          } else if (tmpArr.length == 1) {
            const str = tmpArr[0].remarks?.includes('左') ? '右' : '左';
            return { [`镜片 (${str})`]: `镜片 (${str})` };
          }
          return {
            '镜片 (左)': '镜片 (左)',
            '镜片 (右)': '镜片 (右)'
          };
        } else {
          return undefined as any;
        }
      },
      fieldProps: (form, { rowKey, rowIndex, entity, type }) => {
        return {
          disabled: entity.disabled,
          onChange: (e: any) => {
            const value = e?.target != undefined ? e.target.value : e;
            const goodsItem = getRowByKey(rowKey)[0];
            goodsItem.remarks = value;
            dataSource[rowIndex].remarks = value;
            form.setFieldsValue({ [rowKey || '']: goodsItem });
            setDataSource(Object.assign([], dataSource));
          }
        }
      },
    },
    {
      title: '操作',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 120,
      valueType: 'option',
    }
  ];

  // 输入折扣计算
  const zkChange = (val, rowKey, rowIndex, form, type) => {
    const item = getRowByKey(rowKey)[0];
    if (Number.isFinite(val) && val > 0 && val <= 1) {
      const goodsprice = item['goods_total_price'];

      if (!isNull(goodsprice) && val) {
        let price = parseFloat(val * goodsprice).toFixed(2);
        price = parseFloat(price) <= 0 ? '0.01' : price;
        item['discount_price'] = price;
        dataSource[rowIndex].discount_price = price;
      }
      form.setFieldsValue({ [rowKey || '']: item });
      dataSource[rowIndex].discount = parseFloat(val).toFixed(2);
      setDataSource(Object.assign([], dataSource));
      updateGoodsList(Object.assign([], dataSource));
      checkChange(Object.assign([], dataSource));
    }
  }

  // 输入折扣价计算
  const zkjChange = (val, rowKey, rowIndex, form, type) => {
    const item = getRowByKey(rowKey)[0];
    const total = item['goods_total_price'] || 0;
    if (Number.isFinite(val) && val > 0 && total > 0) {
      const item = getRowByKey(rowKey)[0];
      if (!isNull(total) && val) {
        let discount = parseFloat(parseFloat(val) / parseFloat(total)).toFixed(2);
        discount = parseFloat(discount) <= 0 ? '0.01' : discount;
        item.discount = discount;
        // console.log('total', val, total, discount);
        dataSource[rowIndex].discount = parseFloat(discount).toFixed(2);
      }
      form.setFieldsValue({ [rowKey || '']: item });
      dataSource[rowIndex].discount_price = parseFloat(val).toFixed(2);
      setDataSource(Object.assign([], dataSource));
      updateGoodsList(Object.assign([], dataSource));
      checkChange(Object.assign([], dataSource));
    }
  }
  // 复原
  const onRestore = () => {
    setNewAddNums(0);
    setUpdateNums(0);
    setDeleteNums(0);
    setDataSource(Object.assign([], yuanlist));
    // setDataSource(JSON.parse(JSON.stringify(yuanlist)));
    setTimeout(() => {
      editForm.resetFields();
      updateGoodsList(yuanlist);
    }, 100);
  }

  // 查询商品是否有改动
  const checkChange = (list) => {
    // console.log('checkChange', list, yuanlist)

    let newCount = 0, updateCount = 0;
    list.forEach(element => {
      // 新增的
      if ((element.id).includes('new')) {
        newCount += 1;
      } else { // 原数组里变更的
        // 原数组的商品名称换了
        // eslint-disabled-next-line no-lonely-if
        // eslint-disable-next-line no-lonely-if
        if (element.id !== element.record_id) {
          updateCount += 1;
          element.update = true;
        } else { // 商品名称没换，规格或其他信息有调整
          const ary = yuanlist.filter(item => item.id === element.id);
          if (ary[0].specs_id !== element.specs_id || ary[0].goods_num !== element.goods_num ||
            ary[0].discount !== element.discount || ary[0].discount_price !== element.discount_price) {
            updateCount += 1;
            element.update = true;
          } else {
            element.update = false;
          }
        }

      }
    });
    setNewAddNums(newCount);
    setUpdateNums(updateCount);
  }

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  // 商品规格
  const fetchGoodsSpecsList = async (goods_id: string, goods_dept_code: string, index: number, ary: Array, form, rowKey) => {
    try {
      let data: STOCKGOODSAPI.GoodsSpecsItemList;
      if (initialState?.currentUser?.dept_level === '2') {
        data = await getSubGoodsSpecsList({ goods_id, goods_dept_code, current: 1, pageSize: 10000 })
      } else {
        data = await getGoodsSpecsList({ goods_id, goods_dept_code, current: 1, pageSize: 10000 });
      }
      ary[index].specsList = data.record_list || [];
      if (data.record_list.length === 1) {
        const cur = data.record_list[0];
        if (cur.can_inventory > 0) {
          ggChange(cur, form, rowKey, ary);
          return;
        }
      }
      setDataSource(Object.assign([], ary));
    } catch (error) {
      console.log('error', error)
      showMsg(error?.data?.errmsg);
    }
  }

  useEffect(() => {
    if (list.length > 0) {
      setFilterVal(list[0].goods_dept_code);
    }
    // const result = list.map(item => {return { ...item, disabled: true }})
    setDataSource(Object.assign([], list));
    setEditableRowKeys(list?.map(item => item.id));
  }, [list]);

  // 保存当前行商品信息，并禁用
  const saveCurLine = (row, disabled) => {
    // console.log('row', row, dataSource[row]);
    if (!disabled) {
      editForm.validateFields().then(values => {
        dataSource[row].disabled = true;
        setDataSource(Object.assign([], dataSource));
      }).catch(errorInfo => {
        message.error('请先保存正在编辑的商品信息');
      });
    } else {
      const result = dataSource.filter(item => !item.disabled);
      if (isNull(result) || !result) {
        dataSource[row].disabled = false;
        setDataSource(Object.assign([], dataSource));
      } else {
        message.error('请先保存正在编辑的商品信息');
      }
    }
  }
  const addLine = () => {
    editForm.validateFields().then(values => {
      const result = dataSource.filter(item => !item.disabled);
      if (isNull(result) || !result) {
        const id = `new_${Date.now()}`;
        dataSource.push({ id, specsList: [], disabled: false }),
          setDataSource(Object.assign([], dataSource));
        editableKeys.push(id);
        setEditableRowKeys(Object.assign([], editableKeys));
      } else {
        message.error('请先保存正在编辑的商品信息');
      }
    }).catch(errorInfo => {
      message.error('请先保存正在编辑的商品信息');
    });
  }


  // console.log('dataSource', dataSource)
  return <div className="service-record">
    <div className="header">
      <div className="title">2.商品信息</div>
    </div>
    <Divider style={{ margin: '10px 0 0' }} />
    <EditableProTable<any>
      rowKey="id"
      className='onceTable'
      formRef={formRef}
      actionRef={actionRef}
      style={{ marginTop: -8 }}
      rowClassName={(record) => {
        // console.log('rowClassName', record.id)
        if (record.id === clickRow) {
          return 'tableRowClick';
        }
        if (type === 'edit') {
          if ((record.id || '').includes('new')) {
            return 'new-add';
          }
          if (record.update) {
            return 'update-bg';
          }
        }
        return ''
      }}
      bordered
      value={dataSource}
      onChange={(e) => {
        checkChange(e);
        setDataSource(e)
      }}
      onRow={record => {
        return {
          onClick: event => { setClickRow(record.id) }, // 点击行
          onMouseEnter: event => { }, // 鼠标移入行
          onMouseLeave: event => { },
        };
      }}
      toolbar={
        type === OptType.EDIT ? {
          menu: {
            type: 'inline',
            items: [
              {
                key: 'restore',
                label: <Button className='btnColor2' onClick={onRestore} type="primary" icon={<RedoOutlined />}>变更复原</Button>
              }
            ]
          }
        } : undefined}
      toolBarRender={() => [
        <div>
          {
            type === 'edit' &&
            <>
              <span>新增：</span>
              <span style={{ color: '#52C41A', fontWeight: 'bold' }}>{newAddNums}</span>
              <span style={{ paddingLeft: 20 }}>删除：</span>
              <span style={{ color: '#333', fontWeight: 'bold' }}>{deleteNums}</span>
              <span style={{ paddingLeft: 20 }}>变更：</span>
              <span style={{ color: '#FAAD15', fontWeight: 'bold' }}>{updateNums}</span>
            </>
          }
          <span style={{ paddingLeft: 20 }}>总数：</span>
          <span style={{ color: '#2E8DE6', fontWeight: 'bold' }}>{dataSource.length}</span>
        </div>
      ]}
      recordCreatorProps={
        {
          newRecordType: 'dataSource',
          record: () => ({
            id: `new_${Date.now()}`,
          }),
          style: {
            display: 'none',
          },
        }
      }
      recordCreatorProps={false}
      editable={{
        form: editForm,
        type: 'multiple',
        editableKeys,
        actionRender: (row, config, defaultDoms) => {
          // console.log('row', row);
          const disabled = (dataSource[row.index] || {}).disabled;
          return [
            <a onClick={() => saveCurLine(row.index, disabled)}>{disabled ? '编辑' : '保存'}</a>,
            defaultDoms.delete,
            disabled &&
            <a key="copy" onClick={() => {
              const id = `new_${Date.now()}`;
              dataSource.push({ ...row, id, disabled: false });
              setDataSource(Object.assign([], dataSource));
              editableKeys.push(id);
              setEditableRowKeys(editableKeys);
              updateGoodsList(Object.assign([], dataSource));
            }}>复制</a>]
        },
        onChange: setEditableRowKeys,
        onDelete: async (key, row) => {
          // console.log('ondelete', row)
          const list = dataSource.filter(item => item.id !== row.id);
          setDataSource(Object.assign([], list));
          if (!row.id.includes('new')) {
            setDeleteNums(deleteNums + 1);
          }
          updateGoodsList(Object.assign([], list));
        }
      }}
      columns={columns} />
    <Button onClick={() => addLine()} type="dashed" style={{ width: '100%', marginTop: 10 }} icon={<PlusOutlined />}>添加一行数据</Button>
  </div>
});
export default ItemInfo;
